<template>
  <div class="page-container">
    <router-view v-if="$route.name !== 'ActivityAudit'"></router-view>
    <div v-else>
      <!-- 顶部标题栏 -->
      <header class="header">
        <BackBtn />
        <h1>活动审核管理</h1>
        <Time />
      </header>

      <!-- 主要内容区域 -->
      <div class="main-content" style="margin-top: -70px;">
        <!-- 搜索和筛选区域 -->
        <div class="search-section">
          <el-input v-model="searchText" placeholder="支持搜索活动名称" class="search-input">
            <template #append>
              <el-button type="primary" class="search-btn" @click="handleSearch">
                <el-icon class="search-icon">
                  <Search />
                </el-icon>
              </el-button>
            </template>
          </el-input>

          <div class="filter-section">
            <!-- 日期范围选择 -->
            <div class="date-range-picker">
              <el-date-picker v-model="dateRange[0]" type="date" placeholder="开始日期" class="date-picker"
                @change="handleFilterChange" />
              <span class="separator">—</span>
              <el-date-picker v-model="dateRange[1]" type="date" placeholder="结束日期" class="date-picker"
                @change="handleFilterChange" />
            </div>

            <!-- 时间选择 -->
            <el-select v-model="sortBy" placeholder="排序：提交时间(倒序)" @change="handleFilterChange">
              <el-option label="提交时间(倒序)" value="desc" />
              <el-option label="提交时间(正序)" value="asc" />
            </el-select>

            <!-- 状态筛选 -->
            <el-select v-model="status" placeholder="状态筛选：全部" @change="handleFilterChange">
              <el-option label="状态筛选：全部" value="all" />
              <el-option label="已通过" value="已通过" />
              <el-option label="已驳回" value="已驳回" />
            </el-select>

            <!-- 导出按钮 -->
            <el-button type="danger" :loading="isExporting" @click="handleExcel">导出列表</el-button>
          </div>
        </div>

        <!-- 表格区域 -->
        <div class="table-section">
          <div class="news-list" v-loading="loading" element-loading-text="加载中..."
            :element-loading-background="'rgba(0, 0, 0, 0)'">
            <!-- 添加表头 -->
            <div class="news-header" style="margin-top: -20px;">
              <div class="header-item">活动名称</div>
              <div class="header-item">提交时间</div>
              <div class="header-item">操作</div>
            </div>

            <!-- 数据列表 -->
            <div v-for="(item, index) in tableData" :key="index" class="news-item">
              <div class="line"></div>
              <div class="news-info" @click="handleViewDetail(item)" style="cursor: pointer;">
                <div class="info-value">{{ item.aname }}</div>
                <div class="info-value">{{ item.createdAt }}</div>
              </div>
              <div class="news-actions">
                <el-button v-if="item.status !== '已驳回' && item.status !== '已通过'" type="primary"
                  @click="handleStatusUpdate(item, '已驳回')">驳回</el-button>
                <el-button v-if="item.status !== '已驳回' && item.status !== '已通过'" type="danger"
                  @click="handleStatusUpdate(item, '已通过')">通过</el-button>
                <el-button v-else type="info">{{ item.status }}</el-button>
              </div>
            </div>
          </div>

          <!-- 分页 -->
          <div class="pagination-section">
            <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5, 10, 15]"
              :background="false" layout="prev, pager, next, jumper" :total="total" @size-change="onSizeChange"
              @current-change="onCurrentChange" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted,onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ArrowLeft, Search } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { updateActivityStatus, exportActivities } from '@/api/activitys'
import { useActivityStore } from '@/stores/activitys'
import { storeToRefs } from 'pinia'
import Time from '@/components/Time.vue'
import BackBtn from '@/components/Back-btn.vue'
const router = useRouter()
const activityStore = useActivityStore()
// 从 store 中解构需要的状态
const {
  tableData,
  total,
  pageNum,
  pageSize,
  dateRange,
  status,
  sortBy,
  searchText,
  loading
} = storeToRefs(activityStore)

const isExporting = ref(false)

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return ''
  // 将类似 2025-03-07-12-00 转换为 2025-03-07 12:00
  const parts = timeStr.split('-')
  if (parts.length >= 5) {
    const date = parts.slice(0, 3).join('-')
    const time = parts.slice(3, 5).join(':')
    return `${date} ${time}`
  }
  return timeStr
}

// 格式化表格数据中的时间
const formatTableData = (data) => {
  if (!data) return []
  return data.map(item => ({
    ...item,
    createdAt: formatTime(item.createdAt),
    startTime: formatTime(item.startTime),
    endTime: formatTime(item.endTime),
    submissionTime: formatTime(item.submissionTime)
  }))
}


// 分页处理
const onSizeChange = async (size) => {
  pageSize.value = size
  await activityStore.fetchActivitysData()
  tableData.value = formatTableData(tableData.value)
}

const onCurrentChange = async (num) => {
  pageNum.value = num
  await activityStore.fetchActivitysData()
  tableData.value = formatTableData(tableData.value)
}

// 处理搜索
const handleSearch = async () => {
  pageNum.value = 1
  await activityStore.fetchActivitysData()
  tableData.value = formatTableData(tableData.value)
}

// 筛选条件变化时的处理
const handleFilterChange = async () => {
  pageNum.value = 1
  await activityStore.fetchActivitysData()
  tableData.value = formatTableData(tableData.value)
}

// 处理状态更新
const handleStatusUpdate = async (row, status) => {
  try {
    const confirmText = status === '已通过' ? '通过' : '驳回'
    await ElMessageBox.confirm(
      `确定要${confirmText}该活动吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    const res = await updateActivityStatus({
      aid: row.aid,
      status: status
    })

    if (res.code === 200) {
      ElMessage.success(`${confirmText}成功`)
      // 更新活动状态
      row.status = status
      // 刷新数据
      await activityStore.fetchActivitysData()
      tableData.value = formatTableData(tableData.value)
    } else {
      ElMessage.error(`${confirmText}失败`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

// 导出处理
const handleExcel = async () => {
  try {
    isExporting.value = true
    const response = await exportActivities(
      sortBy.value,
      dateRange.value[0] ? dateRange.value[0].toISOString().split('T')[0] : null,
      dateRange.value[1] ? dateRange.value[1].toISOString().split('T')[0] : null,
      status.value,
      searchText.value
    );

    // 调试信息
    console.log('Response headers:', response.headers);
    console.log('Response type:', response.type);
    console.log('Response size:', response.size);

    // 检查响应是否为空
    if (!response || response.size === 0) {
      throw new Error('导出的文件为空');
    }

    // 检查响应类型
    const contentType = response.type;
    if (!contentType.includes('spreadsheetml.sheet')) {
      // 如果响应不是Excel文件，尝试读取错误信息
      const text = await response.text();
      throw new Error(text || '导出的文件格式不正确');
    }

    // 创建下载链接
    const blob = new Blob([response], { type: contentType });
    const downloadUrl = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = downloadUrl;
    link.download = `活动列表_${new Date().toLocaleDateString()}.xlsx`;
    document.body.appendChild(link);
    link.click();

    // 清理资源
    window.URL.revokeObjectURL(downloadUrl);
    document.body.removeChild(link);

    ElMessage.success('导出成功');
  } catch (error) {
    console.error('Export error:', error);
    ElMessage.error(error.message || '导出失败');
  } finally {
    isExporting.value = false
  }
}

// 查看详情
const handleViewDetail = (row) => {
  router.push(`/activity/info/${row.aid}`)
}

// 重置所有筛选条件的函数
const resetFilters = () => {
  searchText.value = ''  // 重置搜索文本
  dateRange.value = [null, null]  // 重置日期范围
  status.value = 'all'  // 重置状态筛选
  sortBy.value = 'desc'  // 重置时间排序为默认的倒序
  pageNum.value = 1  // 重置页码
  pageSize.value = 10  // 重置每页条数
}

// 在组件挂载时获取活动数据
onMounted(async () => {
  resetFilters()
  loading.value = true
  await activityStore.fetchActivitysData()
  tableData.value = formatTableData(tableData.value)
  loading.value = false
})

// 添加组件卸载钩子
onUnmounted(() => {
  pageNum.value = 1  // 组件卸载时重置页码
})
</script>

<style scoped>
@import '@/assets/css/news/newslist.css';
@import '@/assets/css/header/index.css';
@import '@/assets/css/others/pagination.css';
@import '@/assets/css/others/btn.css';
@import '@/assets/css/others/dateEditor.css';
@import '@/assets/css/others/select.css';
@import '@/assets/css/activity/list.css'; 
.search-section {
    /* background: white; */
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 10px;
    /* box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1); */
    margin-left: 105px;
    min-width: 900px;
    width: 84%;
  }
  
  /* 搜索框特定样式 */
  .search-input {
    margin-bottom: 20px;
  }
  
  .search-input :deep(.el-input__wrapper) {
    height: 40px !important;
    border-radius: 8px 0 0 8px !important;
    padding: 0 12px !important;
    box-sizing: border-box;
  }
  
  .search-input :deep(.el-input:hover .el-input__wrapper) {
    box-shadow: 0 0 0 1px #c62828 inset !important;
  }
  
  .search-input :deep(.el-input__wrapper.is-focus) {
    box-shadow: 0 0 0 1px #c62828 inset !important;
  }
  
  .search-input :deep(.el-input-group__append) {
    padding: 0 !important;
    border: none !important;
    background: none !important;
  }
  
  /* 搜索按钮样式 */
  .search-btn {
    background-color: #c62828 !important;
    border: none;
    height: 40px;
    width: 180px;
    color: white;
    padding: 5px 10px;
    border-radius: 0 8px 8px 0 !important;
    cursor: pointer;
  }
  
  .search-btn:hover {
    background-color: #a91919 !important;
  }
  
  .search-btn .el-icon {
    font-size: 20px;
    color: white;
  }
</style>